package com.niiwoo.civet.trade.listener;

import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.trade.constant.MqConstant;
import com.niiwoo.civet.trade.dao.entity.Project;
import com.niiwoo.civet.trade.dto.request.loan.PushProjectRequestDTO;
import com.niiwoo.civet.trade.service.dubbo.loan.core.ISpeedLoanFactory;
import com.niiwoo.civet.trade.service.dubbo.loan.core.ISpeedLoanService;
import com.niiwoo.civet.trade.service.local.common.ProjectCommonService;
import com.niiwoo.civet.trade.service.local.project.ProjectLocalService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 上标监听器
 * 目的：分离事务与第三方服务调用
 * @author TomXue
 * @since 2018-08-23
 */
@Component
@Slf4j
public class PublishProjectListener {
    @Autowired
    private ProjectCommonService projectCommonService;
    @Autowired
    private ProjectLocalService projectLocalService;
    @Autowired
    private ISpeedLoanFactory iSpeedLoanFactory;

    @RabbitListener(queues = {MqConstant.PROJECT_PUBLISH_QUEUE})
    public void projectWaitPublishHandler(PushProjectRequestDTO pushProjectRequestDTO, Message message, Channel channel) throws IOException {
        try {
            log.info("上标通知,标的ID={},请求参数={}", pushProjectRequestDTO == null ? null : pushProjectRequestDTO.getProjectId(), JSON.toJSONString(pushProjectRequestDTO));
            Project project=projectCommonService.queryProjectBasicInfo(pushProjectRequestDTO.getProjectId());
            ISpeedLoanService service = iSpeedLoanFactory.adaptive(project);

            log.info("上标通知,标的ID={},调用上标接口参数={}", project.getProjectId(), JSON.toJSONString(pushProjectRequestDTO));
            service.pushProject(pushProjectRequestDTO);
        } catch (Exception e) {
            log.error("上标通知,标的ID={},发生系统异常,原因={}", pushProjectRequestDTO == null ? null : pushProjectRequestDTO.getProjectId(), e);
        } finally {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
